package com.eastfair.venuebooking.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.UserAccountDto;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.echo.core.EchoService;
import com.eastfair.venuebooking.dto.*;
import com.eastfair.venuebooking.entity.Project;
import com.eastfair.venuebooking.entity.ProjectExhibition;
import com.eastfair.venuebooking.exceptioncode.VenueBookingExceptionCode;
import com.eastfair.venuebooking.service.ProjectExhibitionService;
import com.eastfair.venuebooking.service.ProjectService;
import com.eastfair.venuebooking.vo.ProjectVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/project")
@Api(value = "Project", tags = "")
@PreAuth(replace = "venuebooking:project:")
public class ProjectController extends SuperController<ProjectService, Long, Project, ProjectPageQuery, ProjectSaveDTO, ProjectUpdateDTO> {

    @Autowired
    private EchoService echoService;

    @Resource
    private UserAccountServiceFeign userAccountServiceFeign;

    @Resource
    private ProjectExhibitionService projectExhibitionService;

    @Override
    public void handlerResult(IPage<Project> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<Project> projectList = list.stream().map((map) -> {
            Project project = Project.builder().build();
            //TODO 请在这里完成转换
            return project;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(projectList));
    }



    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ProjectPageQuery> params) {
        ProjectPageQuery pageQuery = params.getModel();
        //分页处理
        if(ContextUtil.getProjectId()!=null){
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 添加项目
     *
     * @param projectSaveDTO 添加项目
     * @return
     */
    @ApiOperation(value = "添加项目", notes = "添加项目")
    @SysLog("添加项目")
    @PostMapping("/addProject")
    public R addProject(@RequestBody @Validated(ProjectDTO.Check.class) ProjectDTO projectSaveDTO) {
        Project project = new Project();
        project.setProjectName(projectSaveDTO.getProjectName());
        project.setRemark(projectSaveDTO.getRemark());
        project.setExhibitionSum(projectSaveDTO.getExhibitionSum());
        baseService.save(project);
        return R.success(project.getId());
    }

    /**
     * 编辑项目
     *
     * @param projectUpdateDTO 编辑项目
     * @return
     */
    @ApiOperation(value = "编辑项目", notes = "编辑项目")
    @SysLog("修改项目")
    @PostMapping("/updateProject")
    public R updateProject(@RequestBody @Validated(SuperEntity.Update.class) ProjectDTO projectUpdateDTO) {
        Project project = new Project();
        project.setId(projectUpdateDTO.getId());
        project.setProjectName(projectUpdateDTO.getProjectName());
        project.setRemark(projectUpdateDTO.getRemark());
        return R.success( baseService.updateById(project));
    }
    
    /**
     * 项目列表
     * @param params
     * @return
     */
    @ApiOperation(value = "项目列表", notes = "项目列表")
    @PostMapping("/queryProject")
    public R<IPage<ProjectVO>> queryProject(@RequestBody PageParams<ProjectQuery> params) {
        ProjectQuery model = params.getModel();
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Project::getIsDeleted, BusinessConstant.NO)
                .le(Objects.nonNull(model.getId()),Project::getId,model.getId())
                .like(StringUtils.isNotBlank(model.getProjectName()),Project::getProjectName,model.getProjectName())
                .ge(Objects.nonNull(model.getCreateTimeBegin()),Project::getCreateTime,model.getCreateTimeBegin())
                .le(Objects.nonNull(model.getCreateTimeEnd()),Project::getCreateTime,model.getCreateTimeEnd())
                .le(Objects.nonNull(model.getId()),Project::getId,model.getId())
                .orderByDesc(SuperEntity::getCreateTime);
        IPage<Project> page = params.buildPage();
        page = baseService.page(page, queryWrapper);
        IPage<ProjectVO> pageResult = params.buildPage();
        BeanUtils.copyProperties(page,pageResult);
        List<ProjectVO> vos = new ArrayList<>();
        Map<Long, String> names = new HashMap<>(8);
        if(CollectionUtils.isNotEmpty(page.getRecords())){
            try{
                // 联系人电话
                UserAccountDto userAccountDto = new UserAccountDto();
                List<Long> userIds = page.getRecords().stream().map(Project::getCreatedBy).collect(Collectors.toList());
                userAccountDto.setUserIds(userIds);
                R<List<UserAccountVo>> listR = userAccountServiceFeign.querySimpleByIds(userAccountDto);
                if(CollectionUtils.isNotEmpty(listR.getData())){
                    listR.getData().forEach(e->names.put(e.getId(), e.getRealName()));
                }else {
                    log.warn("联系人查询为空 {}",userIds);
                }
            }catch (Exception e){
                log.error("联系人查询失败",e);
            }
        }
        for (Project record : page.getRecords()) {
            ProjectVO projectVO = new ProjectVO();
            BeanUtils.copyProperties(record,projectVO);
            projectVO.setId(record.getId());
            projectVO.setCreatedBy(record.getCreatedBy());
            projectVO.setCreatedName(names.get(record.getCreatedBy()));
            vos.add(projectVO);
        }
        pageResult.setRecords(vos);
        return R.success(pageResult);
    }

    /**
     * 删除项目
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除项目", notes = "删除项目")
    @SysLog("删除项目")
    @GetMapping("/delProject")
    public R<Boolean> delProject(@RequestParam("id") @Validated @NotNull(message = "项目表ID必填") Long id) {
        // 判断项目下是否还有展会
        QueryWrapper<ProjectExhibition> query = new QueryWrapper<>();
        query.lambda().eq(ProjectExhibition::getIsDeleted,BusinessConstant.NO).eq(ProjectExhibition::getExhibitionProjectId,id);
        if (projectExhibitionService.count(query) == 0) {
            // 软删
            Project updateEntity = new Project();
            updateEntity.setId(id);
            updateEntity.setIsDeleted(BusinessConstant.YES);
            return R.success(baseService.updateById(updateEntity));
        }else {
            throw BizException.wrap(VenueBookingExceptionCode.EX_EXIST_CAN_NOT_DELETE);
        }
    }

}
